package logic

import (
	"common/comScript"
	"common/dao/model"
	"context"
	"errors"
	"fmt"
	"gorm.io/gorm"
	"strings"

	"gateway/internal/svc"
	"gateway/internal/types"
	"gateway/websocket/Client"
	websocketType "gateway/websocket/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type SendDataLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewSendDataLogic(ctx context.Context, svcCtx *svc.ServiceContext) *SendDataLogic {
	return &SendDataLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

type data struct {
	Script   string `json:"script"`
	ScriptId int32  `json:"scriptId"`
}

func (l *SendDataLogic) SendData(req *types.SendReq) error {
	// todo: add your logic here and delete this line
	fmt.Println(*req)
	if req.AccountId == "" {
		return errors.New("account id is empty")
	}
	if req.Type == 0 {
		return errors.New("type id is empty")
	}
	if req.TaskId == 0 {
		return errors.New("taskId is empty")
	}
	var sc = model.TaskTable{}
	db := l.svcCtx.DB
	table := db.Table(model.TableNameTaskTable)
	err := table.Transaction(func(tx *gorm.DB) error {
		if err := tx.Where("id = ?", req.TaskId).First(&sc).Error; err != nil {
			return err
		}
		return nil
	})
	if err != nil {
		return err
	}
	AccountIds := strings.Split(req.AccountId, ",")
	mess := websocketType.ServiceMessage{}
	mess.Type = req.Type
	mess.Data = data{
		Script:   comScript.GetString(sc.Script),
		ScriptId: sc.ID,
	}
	err = Client.Send(AccountIds, mess)
	if err != nil {
		return err
	}
	return nil
}
